import { genReqInterface, genResInterface } from './gen';
import { get } from './api';
const create = htmlStr => {
  var template = document.createElement('template');
  template.innerHTML = htmlStr.trim();
  return template.content.firstChild;
};

export const genBtn = async () => {
  const { data } = await get();

  const req = genReqInterface(data);
  const res = genResInterface(data);

  const tpl = `
<div class='tpl-button' style='position: fixed;right: 0;bottom: 0;padding: 30px;'>
    <button>解析</button>
    <button class='type-req' style='margin-left:10px'>复制请求类型定义</button>
    <button class='type-res' style='margin-left:10px'>复制响应类型定义</button>
</div>

  `;
  /** @type {HTMLDivElement} */
  let tplBtn = document.querySelector('.tpl-button');
  if (tplBtn) {
    tplBtn.onclick = null;
    tplBtn.parentNode.removeChild(tplBtn);
  }
  tplBtn = create(tpl);

  document.body.append(tplBtn);

  tplBtn.onclick = function(e) {
    const btn = e.target;
    if (btn.tagName !== 'BUTTON') return;
    if (btn.classList.contains('type-req')) {
      copy(req);
    } else if (btn.classList.contains('type-res')) {
      copy(res);
    } else {
      genBtn();
    }
  };
};

const copy = str => {
  const input = document.createElement('input');
  document.body.appendChild(input);
  input.setAttribute('value', str);
  input.select();
  document.execCommand('copy');
  console.log('复制成功');
  document.body.removeChild(input);
};
